<template>
	<view>
		<u-navbar
			title="订单确认"
			:autoBack="true"
			placeholder
		>
		</u-navbar>
		<scroll-view :scroll-y="true" :style="{height: scrollViewHeight, backgroundColor: '#f5f5f5'}">
			<template v-if="loading">
				<view style="padding: 32rpx;">
					<u-skeleton avatarSize="48" avatarShape="square" style="margin-bottom: 32rpx;" :loading="loading" avatar rows="7" v-for="i in 6" :key="i"></u-skeleton>
				</view>
			</template>
			<template v-else>
				<JoyAddress />
				<view style="height: 16rpx;"/>
				<view class="shop-order-info">
					<view class="shop-order-info-1">
						<u--image radius="8rpx" mode="aspectFill" :src="appInfo.logo[0].url" width="38rpx" height="34rpx"></u--image>
						<view style="width: 16rpx;"/>
						<view class="shop-order-info-11 u-line-1">{{appInfo.name}}</view>
					</view>
					<view :class="['shop-order-info-2', cartDetail.length-1 === index ? null: 'u-border-bottom']" v-for="(shop, index) in cartDetail" :key="shop.id">
						<u--image radius="8rpx" mode="aspectFill" :src="shop.image[0].url" width="160rpx" height="160rpx"></u--image>
						<view style="width: 16rpx;"/>
						<view class="shop-order-info-21">
							<view class="shop-order-info-211 u-line-1">{{shop.goodsName}}</view>
							<view class="shop-order-info-212 u-line-1">{{shop.sku ? shop.sku.sku : ''}}</view>
							<view style="height: 32rpx;"/>
							<view class="shop-order-info-213" @click="showPrice = true">
								<view style="display: flex;align-items: center;">
									<text>&yen;{{shop.price}}</text>
									<text class="iconfont icon-31yiwen" style="padding-left: 8rpx;color: #000;position: relative;top: 2rpx;"></text>
								</view>
								<text style="font-size: 24rpx;color: #666;">x{{shop.buyCount}}</text>
								<!-- <u-number-box :asyncChange="true" @change="onChange(goods, $event)" :buttonSize="24" disabledInput v-model="shop.buyCount"></u-number-box> -->
							</view>
						</view>
					</view>
				</view>
				<view class="shop-order-info-3">
					<view class="shop-order-info-3-item">
						<text class="shop-order-info-3-item-l">商品金额</text>
						<text class="shop-order-info-3-item-r">&yen;{{prices.totalPrice || 0}}</text>
					</view>
					<view class="shop-order-info-3-item">
						<text class="shop-order-info-3-item-l">运费</text>
						<text class="shop-order-info-3-item-r" v-if="prices.freightPrice > 0">&yen;{{prices.freightPrice || 0}}</text>
						<text class="shop-order-info-3-item-r" v-else>免运费</text>
					</view>
					<view class="shop-order-info-3-item">
						<text class="shop-order-info-3-item-l">优惠</text>
						<text class="shop-order-info-3-item-r" style="color: #f40215;">-&yen;{{prices.discount || 0}}</text>
					</view>
					<view class="shop-order-info-3-item" @click="chooseCoupon">
						<text class="shop-order-info-3-item-l">优惠券</text>
						<text class="shop-order-info-3-item-r" style="color: #999;font-weight: normal;" v-if="!curCoupon.id">请选择<text class="iconfont icon-youjiantou"></text> </text>
						<text class="shop-order-info-3-item-r" style="color: #f40215;font-weight: normal;" v-else>-&yen;{{prices.couponPrice || 0}}</text>
					</view>
					<view class="shop-order-info-3-item1">
						<text class="shop-order-info-3-item-l">备注</text>
						<view style="width: 24rpx;"/>
						<view style="flex: 1;">
							<u--input
								placeholderStyle="font-size: 28rpx;"
							    placeholder="请输入备注"
							    border="none"
							    v-model="info.remark"
							  ></u--input>
						</view>
					</view>
				</view>
				<view class="shop-order-pay">
					<JoyPay @changePay="changePay"/>
				</view>
				<view style="height: 32rpx;"/>
			</template>
		</scroll-view>
		<view class="good-detail-bootom" v-if="!loading">
			<view style="margin: 0 32rpx;height: 100%;width: calc(100vw - 64rpx);display: flex;align-items: center;justify-content: space-between;">
				<view class="good-detail-bootom-l1">
					<view class="good-detail-bootom-l1-t">
						<text style="font-weight: bold;color: #333;">合计: </text>
						<text style="padding-left: 8rpx;color: #f40215;font-size: 32rpx;">&yen;{{prices.payPrice || 0}}</text>
					</view>
				</view>	
				<view class="good-detail-bootom-r">
					<u-button @click="toPay" :color="appColor" text="立即支付" shape="circle"></u-button>
				</view>
			</view>	
		</view>
		<u-modal @confirm="showPrice = false" :confirmColor="appColor" width="620rpx" :show="showPrice" title="价格说明" :content='priceDescription'></u-modal>
	</view>
</template>

<script>
	import {mapState, mapActions} from 'vuex';
	import {memberAddress, deleteAddress} from '@/api/me.js';
	import {createOrder, computeOrderPrice} from '@/api/shop.js'
	import JoyAddress from '@/components/joyAddress'
	import JoyPay from '@/components/joyPay'
	export default {
		components: {
			JoyAddress,
			JoyPay
		},
		data() {
			return {
				showPrice: false,
				priceDescription: '因可能存在系统缓存、页面更新导致价格变动异常等不确定情况出现，商品售价以本结算页商品价格为准。',
				count: 1,
				info: {
					count: 1,
					remark: '',
					pay: 1,
					deliveryMethod: 1
				},
				loading: true,
				prices: {}
			}
		},
		computed: {
			...mapState(['appInfo', 'curAddress', 'curCoupon', 'cartDetail']),
			appColor() {
				return this.appPrimaryColor
			},
			scrollViewHeight() {
				return this.scrollHeight - 50 - 44 + 'px';
			},
		},
		watch: {
			curCoupon(val) {
				if(val.id) {
					console.log('---curCoupon');
					this.computeOrderPrice();
				}
			},
			curAddress(val) {
				console.log('curAddress');
				this.computeOrderPrice();
			},
		},
		onLoad() {
			// 清理之前的缓存
			this.setCurCoupon({curCoupon: {}});
			this.address();
		},
		methods: {
			...mapActions(['setCurAddress', 'setCurCoupon']),
			// 计算价格
			computeOrderPrice(count) {
				const {id: couponId} = this.curCoupon;
				const {id: addressId} = this.curAddress;
				let detailList = [];
				let cartList = [];
				this.cartDetail.forEach(item => {
					const {buyCount, goodsId, skuId, cartId} = item;
					let obj = {buyCount, goodsId};
					if(item.sku) {
						obj.skuId = item.sku.id
					}
					detailList.push(obj);
					if(item.cartId) {
						cartList.push(item.cartId);
					}
				})
				let postObj = {
					addressId,
					couponId,
					detailList
				}
				const that = this;
				this.$cuLoading('加载中').then(() => {
					computeOrderPrice(postObj).then(res => {
						const {code, result, message} = res;
						uni.hideLoading();
						if(code === 5001) {
							uni.showModal({
								title: '提示',
								content: '优惠券不可用, 请重新选择',
								confirmColor: that.appColor,
								showCancel: false,
								success: function (res) {
									if (res.confirm) {
										that.setCurCoupon({curCoupon: {}});
										that.prices = result;
									}
								}
							})
						} else if(code === 200) {
							this.prices = res.result
						} else {
							this.$cuTip(message);
						}
					}).catch(() => {
						uni.hideLoading();
					})
				})
				
			},
			// 支付方式改变
			changePay(e) {
				this.info.pay = e;
			},
			address() {
				this.loading = true;
				memberAddress().then(res => {
					let curAddress = res.result.records[0];
					this.setCurAddress({curAddress: curAddress || {}});
				}).finally(() => {
					setTimeout(() => {
						this.loading = false;
					}, 300)
				})
			},
			// 选择地址
			chooseAddress() {
				let url = '/pages/me/address?choose=1';
				this.$cuNavigateTo(url);
			},
			// 选择优惠券
			chooseCoupon() {
				let couponId = this.curCoupon.id || '-1';
				// way 1 商城  way 0 认养
				let url = `/pages/me/chooseCoupon?couponId=${couponId}&way=1`
				this.$cuNavigateTo(url);
			},
			// 支付
			toPay() {
				let that = this;
				const {id: addressId} = this.curAddress;
				const {id: couponId} = this.curCoupon;
				let {remark: buyerRemark, pay: payMethod, deliveryMethod} = this.info;
				let detailList = [];
				let cartList = [];
				this.cartDetail.forEach(item => {
					const {buyCount, goodsId, skuId, cartId} = item;
					let obj = {buyCount, goodsId};
					if(item.sku) {
						obj.skuId = item.sku.id
					}
					detailList.push(obj);
					if(item.cartId) {
						cartList.push(item.cartId);
					}
				})
				buyerRemark = uni.$u.trim(buyerRemark);
				if(!addressId) {
					return this.$cuTip('请选择收货地址');
				}
				
				let postObj = {
					addressId,
					buyerRemark,
					couponId,
					deliveryMethod,
					payMethod,
					detailList
				};
				if(cartList.length>0) {
					postObj.cartList = cartList;
				}
				if(!couponId) {
					delete postObj.couponId
				}
				if(!buyerRemark) {
					delete postObj.buyerRemark
				}
				this.$cuLoading('提交中').then(() => {
					createOrder(postObj).then(res => {
						const {success, result, message, code} = res;
						uni.hideLoading();
						if(success) {
							// 微信支付
							if(postObj.payMethod === 1) {
								const {orderId, wxPayResult: {nonceStr, packageValue, paySign, timeStamp, signType}} = result;
								uni.requestPayment({
									provider: 'wxpay',
									timeStamp,
									nonceStr,
									package: packageValue,
									signType,
									paySign,
									success: function (res) {
										let url = '/pages/shop/paySuccess?id=' + result.orderId;
										uni.redirectTo({
											url
										})
									},
									fail: function (err) {
										console.log('fail:' + JSON.stringify(err));
									}
								})
							// 余额支付	
							} else if (postObj.payMethod === 2){
								let url = '/pages/shop/paySuccess?id=' + result.orderId;
								uni.redirectTo({
									url
								})
							}
						} else {
							if(code === 5001) {
								uni.showModal({
									title: '提示',
									content: '优惠券不可用, 请重新选择',
									confirmColor: that.appColor,
									showCancel: false,
									success: function (res) {
										if (res.confirm) {
											that.setCurCoupon({curCoupon: {}});
										}
									}
								})
							} else {
								this.$cuTip(message);
							}
						}
					}).catch(() => {
						uni.hideLoading();
					})
				})
			},
		}
	}
</script>

<style>
	.u-textarea {
		padding: 9px 0!important;
	}
</style>
<style lang="scss" scoped>
	.shop-order-address {
		position: relative;
		background-color: #fff;
		padding: 32rpx 48rpx 32rpx 32rpx;
		&:after {
			position: absolute;
			right: 0;
			bottom: 0;
			left: 0;
			height: 2px;
			background: -webkit-repeating-linear-gradient(135deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
			background: repeating-linear-gradient(-45deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
			background-size: 120px;
			content: '';
		}
		.shop-order-address-1, .shop-order-address-3 {
			font-size: 28rpx;
			color: #333;
			line-height: 28rpx;
		}
		.shop-order-address-2 {
			font-size: 32rpx;
			line-height: 40rpx;
			color: #333;
			font-weight: bold;
			margin: 16rpx 0;
		}
		.shop-order-address-3 {
			.shop-order-address-31 {
				padding-right: 8rpx;
			}
			.shop-order-address-32 {
				padding-right: 8rpx;
				color: #000;
			}
		}
		.shop-order-address-4 {
			position: absolute;
			right: 16rpx;
			top: 50%;
			transform: translateY(-50%);
			color: #333;
		}
	}
	
	.shop-order-info {
		padding: 32rpx;
		background-color: #fff;
		margin-bottom: 16rpx;
		.shop-order-info-1 {
			display: flex;
			align-items: center;
			margin-bottom: 32rpx;
			.shop-order-info-11 {
				width: calc(100% - 54rpx);
				color: #000;
				line-height: 30rpx;
				font-size: 30rpx;
			}
		}
		.shop-order-info-2 {
			display: flex;
			align-items: center;
			padding-bottom: 32rpx;
			.shop-order-info-21 {
				flex: 1;
				.shop-order-info-211 {
					font-size: 28rpx;
					color: #333;
				}
				.shop-order-info-212 {
					font-size: 24rpx;
					color: #666;
				}
				.shop-order-info-213 {
					display: flex;
					align-items: center;
					justify-content: space-between;
					font-size: 32rpx;
					color: #f40215;
				}
			}
		}
	}
	.shop-order-info-3 {
		padding: 32rpx;
		background-color: #fff;
		margin-bottom: 16rpx;
		.shop-order-info-3-item1 {
			display: flex;
			align-items: center;
			padding: 16rpx 0;
			.shop-order-info-3-item-l {
				font-size: 28rpx;
				line-height: 28rpx;
				color: #333;
			}
		}
		.shop-order-info-3-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 16rpx 0;
			.shop-order-info-3-item-l {
				font-size: 28rpx;
				line-height: 28rpx;
				color: #333;
			}
			.shop-order-info-3-item-r {
				font-size: 28rpx;
				line-height: 28rpx;
				color: #000;
			}
		}
	}
	
	.shop-order-pay {
		padding: 32rpx;
		background-color: #fff;
	}
	
	.good-detail-bootom {
		background-color: #ffffff;
		position: fixed;
		height: 50px;
		width: 100vw;
		bottom: 0;
		left: 0;
		padding-bottom: constant(safe-area-inset-bottom);     /*兼容 iOS<11.2*/
		padding-bottom: env(safe-area-inset-bottom);  /*兼容 iOS>11.2*/
		box-sizing: content-box;
		.good-detail-bootom-l1 {
			display: flex;
			flex-direction: column;
			justify-content: center;
			.good-detail-bootom-l1-t {
				font-size: 28rpx;
				padding-bottom: 4rpx;
			}
			.good-detail-bootom-l1-b {
				.good-detail-bootom-l1-b-1 {
					display: flex;
					align-items: center;
					font-size: 24rpx;
				}
			}
		}
		.good-detail-bootom-r {
			width: 320rpx;
			text-align: right
		}
	}
</style>